<template>
  <form class="validate-from-container">
    <slot name="default"></slot>
    <div class="submit-area d-inline-block"
         @click.prevent="submitForm">
      <slot name="submit">
        <button type="submit"
                class="btn btn-primary ">提交</button>
        <!-- &nbsp;
        <button type="submit"
                class="btn btn-danger"
                @click.prevent="clearInput">重置</button> -->
      </slot>
      &nbsp;
    </div>
    <div class="submit-area d-inline-block"
         @click.prevent="clearInput">
      <slot name="delete">
        <button type="submit"
                class="btn btn-danger ">删除</button>
      </slot>
    </div>
  </form>


</template>

<script lang='ts'>
import { defineComponent, onUnmounted } from 'vue'
// 引入外部组件通信库 定义一个 events 类型 实例化 mitt 的时候，作为泛型传递进去
import mitt from 'mitt'

//定义接收来的验证函数数组的boolean类型
type ValidateFunc = () => boolean
// 无返回值的清空输入框函数类型
type ClearFunc = () => void

// mitt事件类型
type Events = {
  'from-item-created': ValidateFunc
  'from-item-clear': ClearFunc
}

export const emitter = mitt<Events>()

export default defineComponent({
  name: 'ValidateFrom',
  emits: ['form-submit'],
  setup(props, context) {
    let funcArr: ValidateFunc[] = []
    let clearFuncArr: ClearFunc[] = []
    // 处理输入框校验函数数组
    const submitForm = () => {
      const result = funcArr.map(func => func()).every(result => result)
      context.emit('form-submit', result)
    }
    const clearInput = () => {
      clearFuncArr.forEach(func => func())
    }
    //  callback 的 test 的 string 类型和 Events 中的类型对应
    // 回调每个输入框执行的校验函数,装进funcArr函数数组
    const Validatecallback = (func: ValidateFunc) => {
      func && funcArr.push(func)
    }
    // 回调每个输入框执行的清空函数,装进clearFuncArr函数数组
    const Clearcallback = (func: ClearFunc) => {
      func && clearFuncArr.push(func)
      //执行函数数组的清除函数
      clearFuncArr.forEach(func => func())
    }
    emitter.on('from-item-created', Validatecallback)
    emitter.on('from-item-clear', Clearcallback)
    onUnmounted(() => {
      emitter.off('from-item-created', Validatecallback)
      funcArr = []
      emitter.on('from-item-clear', Clearcallback)
      clearFuncArr = []
    })
    return {
      submitForm,
      clearInput
    }
  }
})
</script>

<style scoped>
</style>